import torch
import torch.nn as nn
import torch.nn.functional as F


# 定义残差块ResBlock
# 这里面东西是固定的可以不用动，是残差网络
class ResBlock(nn.Module):
    def __init__(self, inchannel, outchannel, stride=1):
        super(ResBlock, self).__init__()
        # 这里定义了残差块内连续的2个卷积层
        self.left = nn.Sequential(
            nn.Conv2d(inchannel, outchannel, kernel_size=3, stride=stride, padding=1, bias=False),
            nn.BatchNorm2d(outchannel),
            nn.ReLU(inplace=True),
            nn.Conv2d(outchannel, outchannel, kernel_size=3, stride=1, padding=1, bias=False),
            nn.BatchNorm2d(outchannel)
        )
        self.shortcut = nn.Sequential()
        if stride != 1 or inchannel != outchannel:
            # shortcut，这里为了跟2个卷积层的结果结构一致，要做处理
            self.shortcut = nn.Sequential(
                nn.Conv2d(inchannel, outchannel, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(outchannel)
            )

    def forward(self, x):
        out = self.left(x)
        # 将2个卷积层的输出跟处理过的x相加，实现ResNet的基本结构
        out = out + self.shortcut(x)
        out = F.relu(out) # relu激活函数

        return out


class ResNet(nn.Module):
    def __init__(self, ResBlock, num_classes=2):
        super(ResNet, self).__init__()
        self.inchannel = 64
        self.conv1 = nn.Sequential(
                    # 通道数，输出过滤器数量，卷积核大小（二维就是3x3），步长，默认添加0padding
            nn.Conv2d(in_channels=1, out_channels=64, kernel_size=3, stride=1, padding=1),# , bias=False
            nn.BatchNorm2d(64), # 在卷积神经网络的卷积层之后总会添加BatchNorm2d进行数据的归一化处理，这使得数据在进行Relu之前不会因为数据过大而导致网络性能的不稳定
            nn.ReLU()
        )
        self.layer1 = self.make_layer(ResBlock, 64, 2, stride=1) # 步长都是可以调节  2个块  维度通道数64
        self.layer2 = self.make_layer(ResBlock, 128, 2, stride=2)
        self.layer3 = self.make_layer(ResBlock, 256, 2, stride=2)
        self.layer4 = self.make_layer(ResBlock, 512, 2, stride=2)
        self.fc = nn.Linear(512, num_classes)

    # 这个函数主要是用来，重复同一个残差块
    def make_layer(self, block, channels, num_blocks, stride):
        strides = [stride] + [1] * (num_blocks - 1)
        layers = []
        for stride in strides:
            layers.append(block(self.inchannel, channels, stride))
            self.inchannel = channels
        return nn.Sequential(*layers)

    def forward(self, x):
        # 在这里，整个ResNet18的结构就很清晰了
        # 1.输入x维度为[128, 3, 32, 32]
        out = self.conv1(x)             # out维度为[128, 64, 32, 32]
        out = self.layer1(out)          # out维度为[128, 64, 32, 32]
        out = self.layer2(out)          # out维度为[128, 128, 16, 16]
        out = self.layer3(out)          # out维度为[128, 256, 8, 8]
        out = self.layer4(out)          # out维度为[128, 512, 4, 4]
        out = F.avg_pool2d(out, 4)      # out维度为[128, 512, 1, 1]， 也可以考虑F.max_pool2d
        out = out.view(out.size(0), -1) # out维度为[128, 512]
        out = self.fc(out)              # out维度为[128, 10] 因为例子里面为10分类
        return out


def ResNet18():
    return ResNet(ResBlock)